package com.tony.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.comet.CometEvent;
import org.apache.catalina.comet.CometProcessor;
import org.apache.log4j.Logger;

import com.tony.engine.MessageSender;
import com.tony.util.LoggerUtil;

public class CometPushServlet extends HttpServlet implements CometProcessor {

    /**  */
    private static final long    serialVersionUID = -2838804668195403703L;

    private static final Integer TIMEOUT          = 10 * 1000;
    private MessageSender        sender           = null;

    private static final Logger  logger           = Logger.getLogger("engine.log");

    @Override
    public void event(CometEvent event) throws IOException, ServletException {
        HttpServletRequest request = event.getHttpServletRequest();
        HttpServletResponse response = event.getHttpServletResponse();
        if (event.getEventType() == CometEvent.EventType.BEGIN) {
            LoggerUtil.info(logger, "Begin for session: " + request.getSession(true).getId());
            request.setAttribute("org.apache.tomcat.comet.timeout", TIMEOUT);
            sender = new MessageSender(response);
            sender.start();
        } else if (event.getEventType() == CometEvent.EventType.ERROR) {
            LoggerUtil.info(logger, "Error for session: " + request.getSession(true).getId());
            event.close();
        } else if (event.getEventType() == CometEvent.EventType.END) {
            LoggerUtil.info(logger, "End for session: " + request.getSession(true).getId());
            event.close();
        } else if (event.getEventType() == CometEvent.EventType.READ) {
            throw new UnsupportedOperationException("This servlet does not accept data");
        }
    }

    @Override
    public void destroy() {
        sender.interrupt();
        sender = null;
    }

}